package com.wangjw.tuling.zookeeper.own;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;

/**
 * Created by wangjianwen on 2018/12/1.
 */
public class ZookeeperAcl {

    private static final String CONNECT_URL = "47.96.129.248:2181,116.62.115.21:2181,47.96.224.44:2181";

    // 认证类型
    private static final String scheme = "digest";

    // 用户名
    private static final String auth = "123456";

    private ZooKeeper zookeeper;

    public ZookeeperAcl() {
        try {
            zookeeper = new ZooKeeper(CONNECT_URL, 5000, null);
            zookeeper.addAuthInfo(scheme, auth.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 创建持久节点
    public String createPersistent(String path, String data) {
        try {
            return zookeeper.create(path, data.getBytes(), ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
        } catch (KeeperException | InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    // 创建临时节点
    public String createEPhemeral(String path, String data) {
        try {
            return zookeeper.create(path, data.getBytes(), ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.EPHEMERAL);
        } catch (KeeperException | InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getData(String path) throws KeeperException, InterruptedException {
        byte[] data = zookeeper.getData(path, false, null);
        return (data == null) ? null : new String(data);
    }

    public Stat setData(String path, String data) throws KeeperException, InterruptedException {
        return zookeeper.setData(path, data.getBytes(), -1);
    }

    public Stat exists(String path) throws KeeperException, InterruptedException {
        return zookeeper.exists(path, false);
    }

    public void delete(String path) throws KeeperException, InterruptedException {
        zookeeper.delete(path, -1);
    }

    // 递归删除节点
    public void deleteRecursive(String path) throws KeeperException, InterruptedException {
        ZKUtil.deleteRecursive(zookeeper, path);
    }

    public void close() throws InterruptedException {
        zookeeper.close();
    }
}
